package canchaFulbito.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import canchaFulbito.excepcion.DAOExcepcion;
import canchaFulbito.modelo.Local;
import canchaFulbito.util.ConexionBD;
import canchaFulbito.dao.BaseDAO;

public class LocalDAO extends BaseDAO{

	
	public void insertar(Local lo) throws DAOExcepcion {
		System.out.println("LocalDAO: insertar(Local lo)");
		//String query = "INSERT INTO Local(NomLocal,NomDireccion,UrlGoogleMaps,NumTelefono,Ciudad_idCiudad,Persona_IdPersona) VALUES (?,?,?,?,?,?)";
		String query = "INSERT INTO Local(idLocal,NomLocal,NomDireccion,UrlGoogleMaps,NumTelefono,Distrito_idDistrito,Persona_IdPersona) values(?,?,?,?,?,?,?)";
		
		Connection con = null;
		PreparedStatement stmt = null;
		try {
			con = ConexionBD.obtenerConexion();
			stmt = con.prepareStatement(query);
			
			stmt.setInt(1, lo.getIdLocal());
			stmt.setString(2, lo.getNomLocal());
			stmt.setString(3, lo.getNomDireccion());
			stmt.setString(4, lo.getUrlGoogleMaps());
			stmt.setString(5, lo.getNumTelefono());
			stmt.setInt(6, lo.getoDistrito().getIdDistrito());
			stmt.setInt(7, lo.getoPersona().getIdPersona());			
			
			int i = stmt.executeUpdate();
			if (i != 1) {
				throw new SQLException("No se pudo insertar");
			}
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
	}
	public int obtener(String NomLocal) throws DAOExcepcion {
		System.out.println("ServicioDAO: obtener()");
		int lo =0;
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			String query = "Select * From Local where NomLocal=?" ;
			con = ConexionBD.obtenerConexion();
			stmt = con.prepareStatement(query);
			stmt.setString(1, NomLocal);
			rs = stmt.executeQuery();
			if (rs.next()) {
					lo = 1;
			}
			
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return lo;
	}
	
	public int obtener_idLocal() throws DAOExcepcion {
		int idLocal=0;
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			String query = "SELECT COALESCE(max(idLocal),0) idLocal FROM Local" ;
			con = ConexionBD.obtenerConexion();
			stmt = con.prepareStatement(query);
			rs = stmt.executeQuery();
			if (rs.next()) {
				idLocal = Integer.parseInt(rs.getString("idLocal")) + 1;
			}
		} catch (SQLException e) {
		System.err.println(e.getMessage());
		throw new DAOExcepcion(e.getMessage());
		} finally {
		this.cerrarResultSet(rs);
		this.cerrarStatement(stmt);
		this.cerrarConexion(con);
		}
		return idLocal;
		}
}
